<?php
/**
 * @link http://www.tpframe.com/
 * @copyright Copyright (c) 2017 TPFrame Software LLC
 * @author 510974211@qq.com
 */
namespace tpfcore\base;
abstract class SdkSms{
	/**
	 * 申请应用时分配的app_key
	 * @var string
	 */
	protected $AppKey = '';
	
	/**
	 * 申请应用时分配的 app_secret
	 * @var string
	 */
	protected $AppSecret = '';

	/**
	 * 调用接口类型
	 * @var string
	 */
	private $Type = '';
	
	/**
	 * 构造方法，配置应用信息
	 * @param array $token 
	 */
	public function __construct($config=[]){
		//设置SDK类型
		$class = get_class($this);

		$this->Type = strtoupper(substr($class, 0, strlen($class)-3));

		//获取应用配置
		if(empty($config['accessKey'])){
			throw new \Exception('请配置您申请的APP_KEY或APP_SECRET');
		} else {
			$this->AppKey    = isset($config['accessKey'])?$config['accessKey']:"";
			$this->AppSecret = isset($config['accessSecret'])?$config['accessSecret']:"";
		}
	}

	/**
     * 取得Sms实例
     * @static
     * param type  实例化类型
     * param confgig  配置参数
     * @return mixed 返回SmsSdk
     */
    public static function getInstance($type, $config=[]) {

    	$name = ucfirst(strtolower($type)) . 'SDK';
    	
    	if (class_exists("\\tpfcore\\smssdk\\".$name)) {
    		$class="\\tpfcore\\smssdk\\".$name;
    		return new $class($config);
    	} else {
    		throw new \Exception('类不存在'. ':' . $name);
    	}
    }
	
	/**
	 * 发送HTTP请求方法，目前只支持CURL发送请求
	 * @param  string $url    请求URL
	 * @param  array  $params 请求参数
	 * @param  string $method 请求方法GET/POST
	 * @return array  $data   响应数据
	 */
	protected function http($url, $params, $method = 'GET', $header = array(), $multi = false){
		$opts = array(
			CURLOPT_TIMEOUT        => 30,
			CURLOPT_RETURNTRANSFER => 1,
			CURLOPT_SSL_VERIFYPEER => false,
			CURLOPT_SSL_VERIFYHOST => false,
			CURLOPT_HTTPHEADER     => $header
		);

		/* 根据请求类型设置特定参数 */
		switch(strtoupper($method)){
			case 'GET':
				$opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
				break;
			case 'POST':
				//判断是否传输文件
				$params = $multi ? $params : http_build_query($params);
				$opts[CURLOPT_URL] = $url;
				$opts[CURLOPT_POST] = 1;
				$opts[CURLOPT_POSTFIELDS] = $params;
				break;
			default:
				throw new \Exception('不支持的请求方式！');
		}
		
		/* 初始化并执行curl请求 */
		$ch = curl_init();
		curl_setopt_array($ch, $opts);
		$data  = curl_exec($ch);
		$error = curl_error($ch);
		curl_close($ch);
		if($error) throw new \Exception('请求发生错误：' . $error);
		return  $data;
	}
	
	/**
	 * 抽象方法，在SMSSDK中实现
	 * 组装接口调用参数 并调用接口
	abstract protected function call($api, $param = '', $method = 'GET', $multi = false);
	*/
	
	/**
	 * 抽象方法，在SMSSDK中实现
	 * 发送短信
	 */
	// abstract public function sendSms();
}